package svl;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

/**
 * Servlet implementation class subirXML
 */
@WebServlet("/subirXML")
public class subirXML extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public subirXML() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		
		FileItemFactory file_factory = new DiskFileItemFactory();		
		ServletFileUpload servlet_up = new ServletFileUpload(file_factory);
		
		List items = new ArrayList();
		try {
			items = servlet_up.parseRequest(request);
		} catch (FileUploadException e) {			
			e.printStackTrace();
			
			String mensaje = "El archivo a enviar tiene un formato incorrecto o no existe.";
			request.setAttribute("mensaje", mensaje);
			String dire = "/WEB-INF/out/subirXML.jsp";
			RequestDispatcher dispatcher = request.getRequestDispatcher(dire);
		    dispatcher.forward(request, response);
			
		}

		String mensaje = "";
		
			for (int i = 0; i < items.size(); i++) {
			
				FileItem item = (FileItem) items.get(i);
			
				if (!item.isFormField()) {
			
					File archivo_server = new File("c:/subidos/" + item.getName());
			
					try {
						item.write(archivo_server);
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
			
		mensaje = "El archivo fue enviado correctamente.";		
		request.setAttribute("mensaje", mensaje);
		
		String dire = "/WEB-INF/out/subirXML.jsp";
		RequestDispatcher dispatcher = request.getRequestDispatcher(dire);
	    dispatcher.forward(request, response);
	}
}
